package com.cskaoyan.mall.controller.admin;

import com.cskaoyan.mall.model.Result;
import com.cskaoyan.mall.model.User;
import com.cskaoyan.mall.service.UserService;
import com.cskaoyan.mall.service.UserServiceImpl;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

/**
 * User: zsquirrel
 * Date: 2020/4/28
 * Time: 4:00 下午
 */
@WebServlet("/api/admin/user/*")
public class UserServlet extends HttpServlet {

    private UserService userService = new UserServiceImpl();

    Gson gson = new Gson();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        System.out.println(requestURI);
        // login allAdmins...
        String action = requestURI.replace("/api/admin/user/", "");

    }

    /**
     * 登录的具体业务逻辑
     * 1.抓包：抓请求报文（服务器上面、localhost）
     * 2.分析逻辑
     * 3.返回响应报文（响应体，格式是什么样的呢？抓包服务器）
     * @param request
     * @param response
     */


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        String action = requestURI.replace("/api/admin/user/", "");
        if("allUser".equals(action)){
            allUser(request, response);
        }else if("searchUser".equals(action)){
            searchUser(request, response);
        }
    }

    private void searchUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String word = request.getParameter("word");
        List<User> users = userService.searchUser(word);
        response.getWriter().println(gson.toJson(Result.ok(users)));
    }

    private void allUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<User> users = userService.allUser();
        Result result = Result.ok(users);
        response.getWriter().println(gson.toJson(result));
    }

}
